<template>
	<div class="zh-class-position">
		<nav-header></nav-header>
		<div class="zh-table">
			<div class="zh-table-open clear">
				<div class="zh-open-left fl">
					<div class="open-width">
						<el-input v-model="keyword" placeholder="岗位名称" @keyup.enter.native="searchFunc"></el-input>
					</div>
					<el-button type="primary" @click="searchFunc">搜索</el-button>
					<el-button type="primary" @click="reset">重置</el-button>
				</div>
				<div class="zh-open-right fr">
					<el-button type="primary" @click="addBox">新增岗位</el-button>
					<el-button type="danger" @click="deleteMuiltJob_confirm">批量删除</el-button>
				</div>
			</div>
			<div class="zh-table-contents"
				v-loading="loading.status"
			    :element-loading-text="loading.txt"
			>
				<el-table
				    :data="jobData"
				    border
				     @selection-change="tableSelectionChange"
				    max-height="600"
				    style="width: 100%">
				    <el-table-column
				      type="selection"
				      width="50"
				      align="center"
				      fixed>
				    </el-table-column>
					<el-table-column
				      prop=""
				      label="岗位类型"
				      align="center"
				      show-overflow-tooltip
				      >
					  <template slot-scope="scope">
						  {{scope.row.role_name + '岗位'}}
			      	    </template>
				    </el-table-column>
				    <el-table-column
				      prop="name"
				      label="岗位名称"
				      align="center"
				      show-overflow-tooltip
				      >
				    </el-table-column>
				    <!-- <el-table-column
				      prop="4"
				      label="状态"
				      align="center"
				      show-overflow-tooltip
				      >
				      	<template slot-scope="scope">
				      		<el-button plain @click="changeJob_confirm(scope.row,2)" v-if="parseInt(scope.row.status) === 1" size="mini">已启用</el-button>
				      		<el-button plain @click="changeJob_confirm(scope.row,1)" v-if="parseInt(scope.row.status) === 2" size="mini">已禁用</el-button>
				      	</template>
				    </el-table-column> -->
				    <el-table-column
				      prop="5"
				      label="操作"
				      align="center"
				      show-overflow-tooltip
				      >
				      	<template slot-scope="scope">
			      	        <el-button @click="editBox(scope.row)" type="text">编辑</el-button>
			      	        <el-button @click="deleteJob_confirm(scope.row)" type="text" class="delete-button">删除</el-button>
			      	    </template>
				    </el-table-column>
				</el-table>
				<div class="table-pagination" v-show="total_number > 10">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="jobParam.page_index"
						:page-sizes="[10, 20, 30, 40, 50, 100]"
						:page-size="jobParam.page_size"
						layout="total, sizes, prev, pager, next, jumper"
						:total="total_number">
					</el-pagination>
					<div class="pagination-button">
						<el-button 
							@click="getList"
							type="primary" icon="el-icon-refresh" 
							circle title="刷新数据" size="mini" >
						</el-button>
					</div>
				</div>
			</div>
		</div>
		<!-- 添加岗位 -->
		<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="title" :visible.sync="addPost" class="addPost" width="450px">
			<el-form :model="addForm" ref="addForm" :rules="rules" status-icon label-position="left" label-width="90px">
			    <el-form-item label="岗位类型" prop="role_id">
			      	<el-select v-model="addForm.role_id" filterable placeholder="请选择岗位类型">
			        	<el-option
					      v-for="item in roleData"
					      :key="item.id"
					      :label="item.name"
					      :value="item.id">
					    </el-option>
			      	</el-select>
			    </el-form-item>
				<el-form-item label="岗位名称" prop="name">
			      	<el-input 
			      		v-model="addForm.name" 
			      		placeholder="请输入岗位名称，不超过个15个字符" 
			      		autocomplete="off" 
			      		:maxlength="parseInt(15)"
			      		clearable>
			      	</el-input>
			    </el-form-item>
			    <!-- <el-form-item label="岗位状态">
			    	<el-radio v-model="addForm.status" label="1">开启</el-radio>
					<el-radio v-model="addForm.status" label="2">禁用</el-radio>
			    </el-form-item> -->
			    
			    <!-- <el-form-item label="相关科目" >
			      	<el-select v-model="addForm.subject_id" filterable placeholder="请选择科目">
			        	<el-option
					      v-for="item in subjectData"
					      :key="item.id"
					      :label="item.name"
					      :value="item.id">
					    </el-option>
			      	</el-select>
			    </el-form-item> -->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addPost = false">取消</el-button>
			    <el-button type="primary" @click="saveJob">确定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
  	export default {
	    data() {
		    return {
				rowLen: 0,
		    	loading:{
					status:false,
					txt:'获取数据...',
				},
                addPost: false,
                addForm: {
                	id: 0,
                	name: '',
                	status: '1',
                	role_id: null,
                	subject_id: '',
                	user_id: this.$g.user_id
                },
                rules: {
		            name: [
			            { validator: this.validateName, trigger: 'blur', required: true },
		            ],
		            role_id: [
        	            { validator: this.checkChange, trigger: 'change', required: true }
        	        ],
        	       
		        },
                roleData:[],
                roleParam:{
                	user_id:this.$g.user_id,
                	type:1,
                },
               	subjectData:[],
               	jobData:[],
               	jobParam:{
					page_index:1,
					page_size:10,
	        	},
	        	total_number:0,
	        	selected:[],
	        	status_arr:{1:'启用',2:'禁用'},
				title: '',
                keyword: null,
                user_multistage: JSON.parse(sessionStorage.getItem('user_multistage')), // 判断当前是否为多级版本
                user_level: sessionStorage.getItem('user_level') == 'undefined' ? undefined : JSON.parse(sessionStorage.getItem('user_level')), /*判断当前登录会员是否教育局 */
		    }
		},
		created(){
			this.getRoleData();
			this.getSubjectData();
			this.getList();
	    },
	    watch: {
	    	addPost(){
	    		if(this.addPost === false) {
	    			this.$refs.addForm.resetFields()
	    			this.addForm.status = '1'
	    		}
	    	},
	    },
		methods: {
		    getList(){
		    	this.loading.status = true;

				// 重写成功回调
				let success = ( data => {
					console.log(data.data.data)
					this.loading.status = false;
					this.jobData = data.data.data;
					this.total_number = data.data.data_sum;
					this.$forceUpdate();//强制渲染
				});
				let fail = ( data => {
					this.loading.status = false;
					this.$message.error(data.msg)
				})
				let params = Object.assign(this.jobParam, {
					keyword: this.keyword
				})
  				this.$ajax.get('api/user/class_job',{params: params, func:{success:success,fail:fail}})
			},
			searchFunc() {
				this.jobParam.page_index = 1;
				this.jobParam.page_size = 10;
				this.getList();
			},
			reset() {
				this.keyword = null;
				this.jobParam.page_index = 1;
				this.jobParam.page_size = 10;
				this.getList();
			},
		    saveJob(){
		    	this.$refs.addForm.validate((valid) => {
	     			if (valid) {
		            	let success = ( data=>{
		            		this.$message.success(data.msg);
		            		this.addPost = false;
		            		this.getList();
		            	})
		            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
		            	if( !is_empty(this.addForm.id) && parseInt(this.addForm.id) > 0 ){
		            		this.$ajax.put('api/user/class_job',this.addForm,{func:{success:success}})
		            	}else{
							this.$ajax.post('api/user/class_job',this.addForm,{func:{success:success}})
		            	}

		            } else {
		  				return false
		  			}
		  		});
		    },
		    getRoleData(){
                if (this.user_multistage) {
                    if (this.user_level !== 0) {
                        this.addForm.role_id = 6;
                        this.roleData = [ {id: 4, name: "学生岗位"},{id: 5, name: "家长岗位"},{id: 6, name: "教师岗位"} ];
                    }
                } else {
                    this.addForm.role_id = 6;
                    this.roleData = [ {id: 4, name: "学生岗位"},{id: 5, name: "家长岗位"},{id: 6, name: "教师岗位"} ];
                }
                
		    	// 重写成功回调
				// let success = ( data => {
				// 	this.roleData = data.data;
				// 	this.addForm.role_id = this.roleData[0].id
				// });
  		// 		this.$ajax.get('api/user/user_allow_control',{params:this.roleParam,func:{success:success}})
		    	
		    },
		    getSubjectData(){
		    	// 重写成功回调
				let success = ( data => {
					this.subjectData = data.data;
					
					this.addForm.subject_id = this.subjectData[0].id
				});
  				this.$ajax.get('api/cate/simple_subject',{params:{},func:{success:success}})
		    	
		    },
		    deleteJob_confirm(obj){
				let yes = ( data => {
					this.rowLen = 1;
					this.changeJob([obj.id], 0);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.name+' 删除吗？'});

			},
			deleteMuiltJob_confirm(){
				if( this.selected.length === 0 ) {
					this.$message.warning("请选择要删除的岗位");
					return false;
				}
				let yes = ( data => {
					this.deleteMuiltJob();
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定要删除选择的岗位吗？'});

			},
	      	deleteMuiltJob(){
				var ids = [];
				for (var i = this.selected.length - 1; i >= 0; i--) {
					ids.push(this.selected[i].id)
				}

				this.rowLen = this.selected.length;
				this.changeJob(ids, 0);
			},
			changeJob_confirm(obj, status){
				let yes = ( data => {
					this.changeJob(obj.id,status);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.name+' 标记为 '+this.status_arr[parseInt(status)]+' 吗？'});

			},
		    changeJob(id,status){
		    	let success = ( data => {
					this.$message.success(data.msg);

					if (parseInt(status) === 0) {
						if (this.jobData.length - this.rowLen === 0) {
							if (this.jobParam.page_index > 1) {
								this.jobParam.page_index-- ;
							} else {
								this.jobParam.page_index = 1;
							}
						}
					}

					this.getList();
				});
		    	this.$ajax.put('api/user/change_class_job',{id:id,status:status},{func:{success:success}})
		    },
		    handleSizeChange(val) {
		    	this.jobParam.page_index = 1;
		    	this.jobParam.page_size = val;
		    	this.getList();
		    },
		    handleCurrentChange(val) {
		    	this.jobParam.page_index = val;
		    	this.getList();
		    },
		    //选中
		    tableSelectionChange(val) {
                this.selected = val;
            },
            editBox(obj){
            	this.addPost = true;
                this.title = "编辑岗位"
				this.addForm.id = obj.id;
            	this.addForm.name = obj.name
            	this.addForm.status =  obj.status.toString()
                this.addForm.subject_id = parseInt(obj.subject_id) === 0 ? '' :  parseInt(obj.subject_id)
                
                // if (this.user_level) {
            	    this.addForm.role_id = parseInt(obj.role_id)            	    
                //  } else {
            	    // this.addForm.role_id = null;
                //  }
            },
            addBox(){
            	this.title = "添加岗位";
            	this.addPost = true;
				this.addForm.id = '';
            	this.addForm.name = '';
            	this.addForm.status = '1';
                this.addForm.subject_id = '';
                this.addForm.role_id = 6;
            },
            //验证
			validateName(rule, value, callback){
				if (value === '') {
					return callback(new Error('请输入岗位名称'))
				} else if ( !validateName(value)) {
					return callback(new Error('请不要输入空格字符'))
				} else {
					callback()
				}
			},
			checkChange(rule, value, callback){
                if (!isEmpty(value)) {
                    return callback(new Error('请选择'));
                }else{
                    callback()
                }
            },
		},
  	}
</script>
<style lang="scss">
	.zh-class-position {
		.el-table__body-wrapper table tbody {
			td:nth-child(5), td:nth-child(6) {
				padding: 0;
			}
		}
	}
</style>